<!DOCTYPE html>












  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
























<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/css/main.css?v=7.0.1">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.0.1">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.0.1">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.0.1">


  <link rel="mask-icon" href="/images/logo.svg?v=7.0.1" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.0.1',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: true,
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="自从jdk1.5以后，volatile可谓发生了翻天覆地的变化，从一个一直被吐槽的关键词，变成一个轻量级的线程通信代名词。">
<meta name="keywords" content="java,多线程,volatile">
<meta property="og:type" content="article">
<meta property="og:title" content="【java并发编程实战3】解密volatile">
<meta property="og:url" content="http://www.yukonga.cn/2018/09/03/【java并发编程实战3】解密volatile/index.html">
<meta property="og:site_name" content="yukong&#39;s blog">
<meta property="og:description" content="自从jdk1.5以后，volatile可谓发生了翻天覆地的变化，从一个一直被吐槽的关键词，变成一个轻量级的线程通信代名词。">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-062415.jpg">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-062426.jpg">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-055539.jpg">
<meta property="og:updated_time" content="2019-05-07T06:24:45.274Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【java并发编程实战3】解密volatile">
<meta name="twitter:description" content="自从jdk1.5以后，volatile可谓发生了翻天覆地的变化，从一个一直被吐槽的关键词，变成一个轻量级的线程通信代名词。">
<meta name="twitter:image" content="http://cdn.yukonga.cn/2019-05-07-062415.jpg">



  <link rel="alternate" href="/atom.xml" title="yukong's blog" type="application/atom+xml">




  <link rel="canonical" href="http://www.yukonga.cn/2018/09/03/【java并发编程实战3】解密volatile/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>【java并发编程实战3】解密volatile | yukong's blog</title>
  






  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?45b7a3cfe46b3fa2c5d46f59f590664e";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>







  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">yukong's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">learning program</p>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>

      
      
    </ul>
  

  

  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://www.yukonga.cn/2018/09/03/【java并发编程实战3】解密volatile/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="yukong">
      <meta itemprop="description" content="你若对得起时间，时间便对得起你">
      <meta itemprop="image" content="/uploads/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="yukong's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">【java并发编程实战3】解密volatile

              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-09-03 19:19:22" itemprop="dateCreated datePublished" datetime="2018-09-03T19:19:22+08:00">2018-09-03</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-05-07 14:24:45" itemprop="dateModified" datetime="2019-05-07T14:24:45+08:00">2019-05-07</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing"><a href="/categories/java并发编程实战/" itemprop="url" rel="index"><span itemprop="name">java并发编程实战</span></a></span>

                
                
              
            </span>
          

          
            
            
              
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
            
                <span class="post-meta-item-text">评论数：</span>
                <a href="/2018/09/03/【java并发编程实战3】解密volatile/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2018/09/03/【java并发编程实战3】解密volatile/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
            <span id="/2018/09/03/【java并发编程实战3】解密volatile/" class="leancloud_visitors" data-flag-title="【java并发编程实战3】解密volatile">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              
                <span class="post-meta-item-text">阅读次数：</span>
              
                <span class="leancloud-visitors-count"></span>
            </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>自从jdk1.5以后，<code>volatile</code>可谓发生了翻天覆地的变化，从一个一直被吐槽的关键词，变成一个轻量级的线程通信代名词。</p>
<a id="more"></a>
<p>接下来我们将从以下几个方面来分析以下<code>volatile</code>。</p>
<ul>
<li>
<p>重排序与<code>as if serial</code>的关系</p>
</li>
<li>
<p><code>volatile</code>的特点</p>
</li>
<li>
<p><code>volatile</code>的内存语义</p>
</li>
<li>
<p><code>volatile</code>的使用场景</p>
</li>
</ul>
<h2 id="重排序与as-if-serial的关系"><a class="markdownIt-Anchor" href="#重排序与as-if-serial的关系"></a> 重排序与as if serial的关系</h2>
<p>重排序值得是编译器与处理器为了优化程序的性能，而对指令序列进行重新排序的。</p>
<p>但是并不是什么情况下都可以重排序的，</p>
<ul>
<li>
<p>数据依赖</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">a = <span class="number">1</span>;			<span class="comment">// 1</span></span><br><span class="line">b = <span class="number">2</span>;			<span class="comment">// 2</span></span><br></pre></td></tr></table></figure>
<p>在这种情况，1、2不存在数据依赖，是可以重排序的。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">a = <span class="number">1</span>;			<span class="comment">// 1</span></span><br><span class="line">b = a;			<span class="comment">// 2</span></span><br></pre></td></tr></table></figure>
<p>在这种情况，1、2存在数据依赖，是禁止重排序的。</p>
</li>
<li>
<p><code>as if serial</code></p>
<p>简单的理解就是。不管怎么重排序，在单线程情况下程序的执行结果是一致。</p>
</li>
</ul>
<p>根据 <code>as if serial</code>原则，它强调了单线程。那么多线程发生重排序又是怎么样的呢？</p>
<p>请看下面代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">VolatileExample1</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 共享变量 name</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> String name = <span class="string">"init"</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 共享变量 flag</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span>  <span class="keyword">static</span> <span class="keyword">boolean</span> flag = <span class="keyword">false</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">        Thread threadA = <span class="keyword">new</span> Thread(() -&gt; &#123;</span><br><span class="line">            name = <span class="string">"yukong"</span>;			<span class="comment">// 1</span></span><br><span class="line">            flag = <span class="keyword">true</span>;				<span class="comment">// 2</span></span><br><span class="line">        &#125;);</span><br><span class="line">        Thread threadB = <span class="keyword">new</span> Thread(() -&gt; &#123;</span><br><span class="line">            <span class="keyword">if</span> (flag) &#123;   				<span class="comment">// 3</span></span><br><span class="line">                System.out.println(<span class="string">"flag = "</span> + flag + <span class="string">" name = "</span> +name);  <span class="comment">// 4</span></span><br><span class="line">            &#125;;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面代码中，name输出一定是<code>yukong</code>吗，答案是不一定，根据<code>happen-before</code>原则与<code>as if serial</code></p>
<p>原则，由于 1、2不存在依赖关系，可以重排序，操作3、操作4也不存在数据依赖，也可以重排序。</p>
<p>那么就有可能发生下面的情况</p>
<p><img src="http://cdn.yukonga.cn/2019-05-07-062415.jpg" alt=""></p>
<p>上图中，操作1与操作2发生了重排序，程序运行的时候，线程A先将flag更改成true，然后线程B读取flag变量并且判断，由于此时flag已经是true，线程B将继续读取name的值，由于此时线程name的值还没有被线程A写入，那么线程此时输出的name就是初始值，因为在多线程的情况下，重排序存在线程安全问题。</p>
<h2 id="volatile的特点"><a class="markdownIt-Anchor" href="#volatile的特点"></a> volatile的特点</h2>
<p><code>volatile</code>变量具有以下的特点。</p>
<ul>
<li>可见性。对于一个<code>volatile</code>变量的读，总是能看到任意线程对这个变量的最后的修改。</li>
<li>有序性。对于存在指令重排序的情况，<code>volatile</code>会禁止部分指令重排序。</li>
</ul>
<p>这里我先介绍一下<code>volatile</code>关键词的特点，接下来我们将会从它的内存语义来解释，为什么它会具有以上的特点，以及它使用的场景。</p>
<h2 id="volatile的内存语义"><a class="markdownIt-Anchor" href="#volatile的内存语义"></a> volatile的内存语义</h2>
<ul>
<li>当写一个<code>volatile</code>变量时，JMM会<strong>立即</strong>将本地变量中对应的共享变量值刷新到主内存中。</li>
<li>当读一个<code>volatile</code>变量时，JMM会将线程本地变量存储的值，置为无效值，线程接下来将从主内存中读取共享变量。</li>
</ul>
<p>如果一个场景存在对<code>volatile</code>变量的读写场景，在读线程B读一个<code>volatile</code>变量后，，写线程A在写这个<code>volatile</code>变量前所有的所见的共享变量的值都将会立即变得对读线程B可见。</p>
<p>那么这种内存语义是怎么实现的呢？</p>
<p>其实编译器生产字节码的时候，会在指令序列中插入内存屏障来禁止指令排序。下面就是JMM内存屏障插入的策略。</p>
<ul>
<li>在每一个volatile写操作前插入一个StoreStore屏障</li>
<li>在每一个volatile写操作后插入一个StoreLoad屏障</li>
<li>在每一个volatile写操作后插入一个LoadLoad屏障</li>
<li>在每一个volatile读操作后插入一个LoadStore屏障</li>
</ul>
<p>那么这些策略中，插入这些屏障有什么作用呢？我们逐条逐条分析一下。</p>
<ul>
<li>在每一个volatile写操作前插入一个StoreStore屏障，这条策略保证了volatile写变量与之前的普通变量写不会重排序，即是只有当volatile变量之前的普通变量写完，volatile变量才会写。 这样就保证volatile变量写不会跟它之前的普通变量写重排序</li>
<li>在每一个volatile写操作后插入一个StoreLoad屏障，这条策略保证了volatile写变量与之后的volatile写/读不会重排序，即是只有当volatile变量写完之后，你后面的volatile读写才能操作。 这样就保证volatile变量写不会跟它之后的普通变量读重排序</li>
<li>在每一个volatile读操作后插入一个LoadLoad屏障，这条策略保证了volatile读变量与之后的普通读不会重排序，即只有当前volatile变量读完，之后的普通读才能读。 这样就保证volatile变量读不会跟它之后的普通变量读重排序</li>
<li>在每一个volatile读操作后插入一个LoadStore屏障，这条策略保证了volatile读变量与之后的普通写不会重排序，即只有当前volatile变量读完，之后的普通写才能写。样就保证volatile变量读不会跟它之后的普通变量写重排序</li>
</ul>
<p>根据这些策略，volatile变量禁止了部分的重排序，这样也是为什么我们会说volatile具有一定的有序的原因。</p>
<p>根据以上分析的<code>volatile</code>的内存语义，大家也就知道了为什么前面我们提到的<code>happen-before</code>原则会有一条</p>
<ul>
<li>volatile的写happen-before与volaile的读。</li>
</ul>
<p>那么根据<code>volatile</code>的内存语义，我们只需要更改之前的部分代码，只能让它正确的执行。</p>
<p>即把flag定义成一个<code>volatile</code>变量即可。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">VolatileExample1</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 共享变量 name</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> String name = <span class="string">"init"</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 共享变量 flag</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span>  <span class="keyword">volatile</span> <span class="keyword">static</span> <span class="keyword">boolean</span> flag = <span class="keyword">false</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">        Thread threadA = <span class="keyword">new</span> Thread(() -&gt; &#123;</span><br><span class="line">            name = <span class="string">"yukong"</span>;			<span class="comment">// 1</span></span><br><span class="line">            flag = <span class="keyword">true</span>;				<span class="comment">// 2</span></span><br><span class="line">        &#125;);</span><br><span class="line">        Thread threadB = <span class="keyword">new</span> Thread(() -&gt; &#123;</span><br><span class="line">            <span class="keyword">if</span> (flag) &#123;   				<span class="comment">// 3</span></span><br><span class="line">                System.out.println(<span class="string">"flag = "</span> + flag + <span class="string">" name = "</span> +name);  <span class="comment">// 4</span></span><br><span class="line">            &#125;;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>我们来分析一下</p>
<ul>
<li>
<p>由于 flag是volatile变量 那么在volatile写之前插入一个storestore内存屏障，所以1,2不会发生重排序,即1happen before 2</p>
</li>
<li>
<p>由于 flag是volatile变量 那么在volatile读之后插入一个loadload内存屏障，所以3,4不会发生重排序,即3happen before 4</p>
</li>
<li>
<p>根据happen-before原则，volatile写happen before volatile读，即是 2happen before 3。</p>
</li>
<li>
<p>根据happen-before的传递性，所以1 happen before4。</p>
</li>
</ul>
<p><img src="http://cdn.yukonga.cn/2019-05-07-062426.jpg" alt=""></p>
<h1 id="volatile的使用场景"><a class="markdownIt-Anchor" href="#volatile的使用场景"></a> volatile的使用场景</h1>
<ul>
<li>标记变量，也就是上面的flag使用</li>
<li>double check 单例模式中</li>
</ul>
<p>下面我们看看double check的使用</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Singleton</span></span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">volatile</span> <span class="keyword">static</span> Singleton instance = <span class="keyword">null</span>;</span><br><span class="line">     </span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="title">Singleton</span><span class="params">()</span> </span>&#123;</span><br><span class="line">         </span><br><span class="line">    &#125;</span><br><span class="line">     </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Singleton <span class="title">getInstance</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(instance==<span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (Singleton.class) &#123;</span><br><span class="line">                <span class="keyword">if</span>(instance==<span class="keyword">null</span>)</span><br><span class="line">                    instance = <span class="keyword">new</span> Singleton();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> instance;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>至于为何需要这么写请参考：</p>
<p>《Java 中的双重检查（Double-Check）》<a href="http://www.iteye.com/topic/652440" target="_blank" rel="noopener">http://www.iteye.com/topic/652440</a></p>
<p>最后大家希望关注一下我的个人公众号。<br>
欢迎大家关注一下我的个人公众号。一起交流一起学习，有问必答。</p>
<p><img src="http://cdn.yukonga.cn/2019-05-07-055539.jpg" alt=""></p>

      
    </div>

    

    
    
    

    

    
      
    
    
      <div>
        <div id="reward-container">
  <div>喜欢就请博主喝个☕️吧</div>
  <button id="reward-button" disable="enable" onclick="var qr = document.getElementById(&quot;qr&quot;); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">

    
      
      
        
      
      <div style="display: inline-block">
        <img src="/images/wechatpay.jpg" alt="yukong 微信支付">
        <p>微信支付</p>
      </div>
    
      
      
        
      
      <div style="display: inline-block">
        <img src="/images/alipay.jpg" alt="yukong 支付宝">
        <p>支付宝</p>
      </div>
    

  </div>
</div>

      </div>
    

    
      <div>
        




  



<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>yukong</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    
    <a href="http://www.yukonga.cn/2018/09/03/【java并发编程实战3】解密volatile/" title="【java并发编程实战3】解密volatile">http://www.yukonga.cn/2018/09/03/【java并发编程实战3】解密volatile/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc/4.0/" rel="noopener" target="_blank"><i class="fa fa-fw fa-creative-commons"></i>BY-NC</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    
    

      <div>
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag"><i class="fa fa-tag"></i> java</a>
          
            <a href="/tags/多线程/" rel="tag"><i class="fa fa-tag"></i> 多线程</a>
          
            <a href="/tags/volatile/" rel="tag"><i class="fa fa-tag"></i> volatile</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/08/30/【java并发编程实战2】无锁编程CAS与atomic包/" rel="next" title="【java并发编程实战2】无锁编程CAS与atomic包">
                <i class="fa fa-chevron-left"></i> 【java并发编程实战2】无锁编程CAS与atomic包
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/09/04/【SpringBoot2-0系列11】SpringBoot之-Elasticsearch完成CURD/" rel="prev" title="【SpringBoot2.0系列11】SpringBoot之@Elasticsearch完成CURD">
                【SpringBoot2.0系列11】SpringBoot之@Elasticsearch完成CURD <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div class="comments" id="comments">
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/uploads/avatar.png" alt="yukong">
            
              <p class="site-author-name" itemprop="name">yukong</p>
              <div class="site-description motion-element" itemprop="description">你若对得起时间，时间便对得起你</div>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">26</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                      <a href="/categories/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">6</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  
                    
                      <a href="/tags/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">36</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://github.com/YuKongEr" title="GitHub &rarr; https://github.com/YuKongEr" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="mailto:yukongcode@gmail.com" title="E-Mail &rarr; mailto:yukongcode@gmail.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://www.jianshu.com/u/bc2e35b66293" title="简书 &rarr; https://www.jianshu.com/u/bc2e35b66293" rel="noopener" target="_blank"><i class="fa fa-fw fa-skype"></i>简书</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://blog.csdn.net/xp541130126" title="csdn &rarr; https://blog.csdn.net/xp541130126" rel="noopener" target="_blank"><i class="fa fa-fw fa-vk"></i>csdn</a>
                </span>
              
            </div>
          

          

          
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#重排序与as-if-serial的关系"><span class="nav-number">1.</span> <span class="nav-text"> 重排序与as if serial的关系</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#volatile的特点"><span class="nav-number">2.</span> <span class="nav-text"> volatile的特点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#volatile的内存语义"><span class="nav-number">3.</span> <span class="nav-text"> volatile的内存语义</span></a></li></ol><li class="nav-item nav-level-1"><a class="nav-link" href="#volatile的使用场景"><span class="nav-number"></span> <span class="nav-text"> volatile的使用场景</span></a></li></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">yukong</span>

  

  
</div>
<div class="BbeiAn-info">
浙ICP备 -
<a target="_blank" href="http://www.miitbeian.gov.cn">19015067号</a>

</div>









        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="post-meta-item-icon">
      <i class="fa fa-user"></i>
      您是访问本站的第&nbsp
    </span>
    <span class="site-uv" title="总访客量">
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      &nbsp 位朋友
    </span>
  

  
    <span class="post-meta-divider">|</span>
  

  
    <span class="post-meta-item-icon">
      <i class="fa fa-eye"></i>
      本站总共访问&nbsp
    </span>
    <span class="site-pv" title="总访问量">
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>









        
      </div>
    </footer>

    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  <script src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>


  


  <script src="/js/src/utils.js?v=7.0.1"></script>

  <script src="/js/src/motion.js?v=7.0.1"></script>



  
  


  <script src="/js/src/affix.js?v=7.0.1"></script>

  <script src="/js/src/schemes/pisces.js?v=7.0.1"></script>




  
  <script src="/js/src/scrollspy.js?v=7.0.1"></script>
<script src="/js/src/post-details.js?v=7.0.1"></script>



  


  <script src="/js/src/next-boot.js?v=7.0.1"></script>


  

  

  

  
  

<script src="//cdn1.lncld.net/static/js/3.11.1/av-min.js"></script>



<script src="//unpkg.com/valine/dist/Valine.min.js"></script>

<script>
  var GUEST = ['nick', 'mail', 'link'];
  var guest = 'nick,mail,link';
  guest = guest.split(',').filter(function(item) {
    return GUEST.indexOf(item) > -1;
  });
  new Valine({
    el: '#comments',
    verify: false,
    notify: false,
    appId: 'UXuVTqzKQgCJRWTkO8K60EXL-gzGzoHsz',
    appKey: 'n3ohmj1CGAM1GUfp6SqF4LXh',
    placeholder: 'Just go go',
    avatar: 'mm',
    meta: guest,
    pageSize: '10' || 10,
    visitor: false,
    lang: 'zh-cn' || 'zh-cn'
  });
</script>




  


  




  
  
  <script>
    
    function addCount(Counter) {
      var $visitors = $('.leancloud_visitors');
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();

      Counter('get', '/classes/Counter', { where: JSON.stringify({ url }) })
        .done(function({ results }) {
          if (results.length > 0) {
            var counter = results[0];
            
            Counter('put', '/classes/Counter/' + counter.objectId, JSON.stringify({ time: { '__op': 'Increment', 'amount': 1 } }))
            
              .done(function() {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.time + 1);
              })
            
              .fail(function ({ responseJSON }) {
                console.log('Failed to save Visitor num, with error message: ' + responseJSON.error);
              })
          } else {
            
              Counter('post', '/classes/Counter', JSON.stringify({ title: title, url: url, time: 1 }))
                .done(function() {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(1);
                })
                .fail(function() {
                  console.log('Failed to create');
                });
            
          }
        })
        .fail(function ({ responseJSON }) {
          console.log('LeanCloud Counter Error: ' + responseJSON.code + ' ' + responseJSON.error);
        });
    }
    

    $(function() {
      $.get('https://app-router.leancloud.cn/2/route?appId=' + 'UXuVTqzKQgCJRWTkO8K60EXL-gzGzoHsz')
        .done(function({ api_server }) {
          var Counter = function(method, url, data) {
            return $.ajax({
              method: method,
              url: 'https://' + api_server + '/1.1' + url,
              headers: {
                'X-LC-Id': 'UXuVTqzKQgCJRWTkO8K60EXL-gzGzoHsz',
                'X-LC-Key': 'n3ohmj1CGAM1GUfp6SqF4LXh',
                'Content-Type': 'application/json',
              },
              data: data
            });
          };
          
            addCount(Counter);
          
        });
    });
  </script>



  

  

  

  

  

  

  

  

  

  

  
<script>
  $('.highlight').each(function(i, e) {
    var $wrap = $('<div>').addClass('highlight-wrap');
    $(e).after($wrap);
    $wrap.append($('<button>').addClass('copy-btn').append('复制').on('click', function(e) {
      var code = $(this).parent().find('.code').find('.line').map(function(i, e) {
        return $(e).text();
      }).toArray().join('\n');
      var ta = document.createElement('textarea');
      var yPosition = window.pageYOffset || document.documentElement.scrollTop;
      ta.style.top = yPosition + 'px'; // Prevent page scroll
      ta.style.position = 'absolute';
      ta.style.opacity = '0';
      ta.readOnly = true;
      ta.value = code;
      document.body.appendChild(ta);
      ta.select();
      ta.setSelectionRange(0, code.length);
      ta.readOnly = false;
      var result = document.execCommand('copy');
      
        if (result) $(this).text('复制成功');
        else $(this).text('复制失败');
      
      ta.blur(); // For iOS
      $(this).blur();
    })).on('mouseleave', function(e) {
      var $b = $(this).find('.copy-btn');
      setTimeout(function() {
        $b.text('复制');
      }, 300);
    }).append(e);
  })
</script>


  

  

</body>
</html>
